{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Precision-Recall\n\n\nExample of Precision-Recall metric to evaluate classifier output quality.\n\nPrecision-Recall is a useful measure of success of prediction when the\nclasses are very imbalanced. In information retrieval, precision is a\nmeasure of result relevancy, while recall is a measure of how many truly\nrelevant results are returned.\n\nThe precision-recall curve shows the tradeoff between precision and\nrecall for different threshold. A high area under the curve represents\nboth high recall and high precision, where high precision relates to a\nlow false positive rate, and high recall relates to a low false negative\nrate. High scores for both show that the classifier is returning accurate\nresults (high precision), as well as returning a majority of all positive\nresults (high recall).\n\nA system with high recall but low precision returns many results, but most of\nits predicted labels are incorrect when compared to the training labels. A\nsystem with high precision but low recall is just the opposite, returning very\nfew results, but most of its predicted labels are correct when compared to the\ntraining labels. An ideal system with high precision and high recall will\nreturn many results, with all results labeled correctly.\n\nPrecision ($P$) is defined as the number of true positives ($T_p$)\nover the number of true positives plus the number of false positives\n($F_p$).\n\n$P = \\frac{T_p}{T_p+F_p}$\n\nRecall ($R$) is defined as the number of true positives ($T_p$)\nover the number of true positives plus the number of false negatives\n($F_n$).\n\n$R = \\frac{T_p}{T_p + F_n}$\n\nThese quantities are also related to the ($F_1$) score, which is defined\nas the harmonic mean of precision and recall.\n\n$F1 = 2\\frac{P \\times R}{P+R}$\n\nNote that the precision may not decrease with recall. The\ndefinition of precision ($\\frac{T_p}{T_p + F_p}$) shows that lowering\nthe threshold of a classifier may increase the denominator, by increasing the\nnumber of results returned. If the threshold was previously set too high, the\nnew results may all be true positives, which will increase precision. If the\nprevious threshold was about right or too low, further lowering the threshold\nwill introduce false positives, decreasing precision.\n\nRecall is defined as $\\frac{T_p}{T_p+F_n}$, where $T_p+F_n$ does\nnot depend on the classifier threshold. This means that lowering the classifier\nthreshold may increase recall, by increasing the number of true positive\nresults. It is also possible that lowering the threshold may leave recall\nunchanged, while the precision fluctuates.\n\nThe relationship between recall and precision can be observed in the\nstairstep area of the plot - at the edges of these steps a small change\nin the threshold considerably reduces precision, with only a minor gain in\nrecall.\n\n**Average precision** (AP) summarizes such a plot as the weighted mean of\nprecisions achieved at each threshold, with the increase in recall from the\nprevious threshold used as the weight:\n\n$\\text{AP} = \\sum_n (R_n - R_{n-1}) P_n$\n\nwhere $P_n$ and $R_n$ are the precision and recall at the\nnth threshold. A pair $(R_k, P_k)$ is referred to as an\n*operating point*.\n\nAP and the trapezoidal area under the operating points\n(:func:`sklearn.metrics.auc`) are common ways to summarize a precision-recall\ncurve that lead to different results. Read more in the\n`User Guide <precision_recall_f_measure_metrics>`.\n\nPrecision-recall curves are typically used in binary classification to study\nthe output of a classifier. In order to extend the precision-recall curve and\naverage precision to multi-class or multi-label classification, it is necessary\nto binarize the output. One curve can be drawn per label, but one can also draw\na precision-recall curve by considering each element of the label indicator\nmatrix as a binary prediction (micro-averaging).\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>See also :func:`sklearn.metrics.average_precision_score`,\n             :func:`sklearn.metrics.recall_score`,\n             :func:`sklearn.metrics.precision_score`,\n             :func:`sklearn.metrics.f1_score`</p></div>\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In binary classification settings\n--------------------------------------------------------\n\nCreate simple data\n..................\n\nTry to differentiate the two first classes of the iris data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn import svm, datasets\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\n# Add noisy features\nrandom_state = np.random.RandomState(0)\nn_samples, n_features = X.shape\nX = np.c_[X, random_state.randn(n_samples, 200 * n_features)]\n\n# Limit to the two first classes, and split into training and test\nX_train, X_test, y_train, y_test = train_test_split(X[y < 2], y[y < 2],\n                                                    test_size=.5,\n                                                    random_state=random_state)\n\n# Create a simple classifier\nclassifier = svm.LinearSVC(random_state=random_state)\nclassifier.fit(X_train, y_train)\ny_score = classifier.decision_function(X_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Compute the average precision score\n...................................\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.metrics import average_precision_score\naverage_precision = average_precision_score(y_test, y_score)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot the Precision-Recall curve\n................................\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import plot_precision_recall_curve\nimport matplotlib.pyplot as plt\n\ndisp = plot_precision_recall_curve(classifier, X_test, y_test)\ndisp.ax_.set_title('2-class Precision-Recall curve: '\n                   'AP={0:0.2f}'.format(average_precision))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In multi-label settings\n------------------------\n\nCreate multi-label data, fit, and predict\n...........................................\n\nWe create a multi-label dataset, to illustrate the precision-recall in\nmulti-label settings\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.preprocessing import label_binarize\n\n# Use label_binarize to be multi-label like settings\nY = label_binarize(y, classes=[0, 1, 2])\nn_classes = Y.shape[1]\n\n# Split into training and test\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5,\n                                                    random_state=random_state)\n\n# We use OneVsRestClassifier for multi-label prediction\nfrom sklearn.multiclass import OneVsRestClassifier\n\n# Run classifier\nclassifier = OneVsRestClassifier(svm.LinearSVC(random_state=random_state))\nclassifier.fit(X_train, Y_train)\ny_score = classifier.decision_function(X_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The average precision score in multi-label settings\n....................................................\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import average_precision_score\n\n# For each class\nprecision = dict()\nrecall = dict()\naverage_precision = dict()\nfor i in range(n_classes):\n    precision[i], recall[i], _ = precision_recall_curve(Y_test[:, i],\n                                                        y_score[:, i])\n    average_precision[i] = average_precision_score(Y_test[:, i], y_score[:, i])\n\n# A \"micro-average\": quantifying score on all classes jointly\nprecision[\"micro\"], recall[\"micro\"], _ = precision_recall_curve(Y_test.ravel(),\n    y_score.ravel())\naverage_precision[\"micro\"] = average_precision_score(Y_test, y_score,\n                                                     average=\"micro\")\nprint('Average precision score, micro-averaged over all classes: {0:0.2f}'\n      .format(average_precision[\"micro\"]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot the micro-averaged Precision-Recall curve\n...............................................\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.figure()\nplt.step(recall['micro'], precision['micro'], where='post')\n\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nplt.ylim([0.0, 1.05])\nplt.xlim([0.0, 1.0])\nplt.title(\n    'Average precision score, micro-averaged over all classes: AP={0:0.2f}'\n    .format(average_precision[\"micro\"]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot Precision-Recall curve for each class and iso-f1 curves\n.............................................................\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from itertools import cycle\n# setup plot details\ncolors = cycle(['navy', 'turquoise', 'darkorange', 'cornflowerblue', 'teal'])\n\nplt.figure(figsize=(7, 8))\nf_scores = np.linspace(0.2, 0.8, num=4)\nlines = []\nlabels = []\nfor f_score in f_scores:\n    x = np.linspace(0.01, 1)\n    y = f_score * x / (2 * x - f_score)\n    l, = plt.plot(x[y >= 0], y[y >= 0], color='gray', alpha=0.2)\n    plt.annotate('f1={0:0.1f}'.format(f_score), xy=(0.9, y[45] + 0.02))\n\nlines.append(l)\nlabels.append('iso-f1 curves')\nl, = plt.plot(recall[\"micro\"], precision[\"micro\"], color='gold', lw=2)\nlines.append(l)\nlabels.append('micro-average Precision-recall (area = {0:0.2f})'\n              ''.format(average_precision[\"micro\"]))\n\nfor i, color in zip(range(n_classes), colors):\n    l, = plt.plot(recall[i], precision[i], color=color, lw=2)\n    lines.append(l)\n    labels.append('Precision-recall for class {0} (area = {1:0.2f})'\n                  ''.format(i, average_precision[i]))\n\nfig = plt.gcf()\nfig.subplots_adjust(bottom=0.25)\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nplt.title('Extension of Precision-Recall curve to multi-class')\nplt.legend(lines, labels, loc=(0, -.38), prop=dict(size=14))\n\n\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}